package com.alex.wechat.mp.account.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.MyBeanUtils;
import org.jeecgframework.core.util.ResourceUtil;
import org.jeecgframework.core.util.StringUtil;
import org.jeecgframework.core.util.oConvertUtils;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.system.service.SystemService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alex.wechat.mp.account.entity.WxAccountEntity;
import com.alex.wechat.mp.account.service.WxAccountServiceI;
import com.alex.wechat.mp.accountmgr.entity.WxAccountMgrEntity;
import com.gomore.jeecg.common.Assert;
import com.gomore.jeecg.jpa.query.QueryOrderDirection;
import com.gomore.jeecg.jpa.query.SQLSubquery;

/**
 * @Title: Controller
 * @Description: 微信公众帐号信息
 * @author onlineGenerator
 * @date 2014-05-21 00:53:47
 * @version V1.0
 */
@Controller
@RequestMapping("/wxAccountController")
public class WxAccountController extends BaseController {
  /**
   * Logger for this class
   */
  private static final Logger logger = Logger.getLogger(WxAccountController.class);

  @Autowired
  private WxAccountServiceI accountService;

  @Autowired
  private SystemService systemService;

  /**
   * 微信公众帐号信息列表 页面跳转
   * 
   * @return
   */
  @RequestMapping(params = "list")
  public ModelAndView weixinAccount(HttpServletRequest request) {
    return new ModelAndView("com/gomore/wechat/mp/account/wxAccountList");
  }

  /**
   * easyui AJAX请求数据
   * 
   * @param request
   * @param response
   * @param dataGrid
   * @param user
   */

  @RequestMapping(params = "datagrid")
  public void datagrid(WxAccountEntity weixinAccount, HttpServletRequest request,
      HttpServletResponse response, DataGrid dataGrid) {
    SQLSubquery query = new SQLSubquery(WxAccountEntity.class, "o");
    query.addSelect("distinct(o)");

    if (!ResourceUtil.isAdmin()) {
      // 如果不是管理员，则只列出其管理的微信公众号
      query.addJoinEntity(WxAccountMgrEntity.class, "m", "o.id = m.accountId");
      query.appendCondition("m.userId = :userId", ResourceUtil.getSessionUserId());
    }

    if (!StringUtils.isBlank(dataGrid.getSort())) {
      query.appendOrder("o." + dataGrid.getSort(), dataGrid.getOrder() == null
          ? QueryOrderDirection.asc : QueryOrderDirection.valueOf(dataGrid.getOrder().name()));
    }
    this.accountService.query(query, dataGrid);
    TagUtil.datagrid(response, dataGrid);
  }

  /**
   * 删除微信公众帐号信息
   * 
   * @return
   */
  @RequestMapping(params = "doDel")
  @ResponseBody
  public AjaxJson doDel(WxAccountEntity weixinAccount, HttpServletRequest request) {
    AjaxJson j = new AjaxJson();
    weixinAccount = systemService.getEntity(WxAccountEntity.class, weixinAccount.getId());
    String message = "微信公众帐号信息删除成功";
    try {
      accountService.delete(weixinAccount);
      systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
    } catch (Exception e) {
      e.printStackTrace();
      message = "微信公众帐号信息删除失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  /**
   * 删除微信公众帐号信息
   * 
   * @return
   */
  @RequestMapping(params = "doActive")
  @ResponseBody
  public AjaxJson doActive(WxAccountEntity account, HttpServletRequest request) {
    AjaxJson j = new AjaxJson();

    String message = "微信公众帐号设置成功";
    try {
      accountService.active(account.getId());
      j.setSuccess(true);
      systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
    } catch (Exception e) {
      logger.error("", e);
      j.setSuccess(false);
      message = "微信公众帐号设置失败: " + e.getMessage();
    }

    j.setMsg(message);
    return j;
  }

  /**
   * 批量删除微信公众帐号信息
   * 
   * @return
   */
  @RequestMapping(params = "doBatchDel")
  @ResponseBody
  public AjaxJson doBatchDel(String ids, HttpServletRequest request) {
    AjaxJson j = new AjaxJson();

    String message = "微信公众帐号信息删除成功";
    try {
      for (String id : ids.split(",")) {
        WxAccountEntity weixinAccount = systemService.getEntity(WxAccountEntity.class, id);
        accountService.delete(weixinAccount);
        systemService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO);
      }
    } catch (Exception e) {
      e.printStackTrace();
      message = "微信公众帐号信息删除失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  /**
   * 添加微信公众帐号信息
   * 
   * @param ids
   * @return
   */
  @RequestMapping(params = "doAdd")
  @ResponseBody
  public AjaxJson doAdd(WxAccountEntity account, HttpServletRequest request) {
    AjaxJson j = new AjaxJson();

    String message = "微信公众帐号信息添加成功";
    try {
      WxAccountEntity oldAccount = accountService.getAccountByOriginalId(account.getOriginalId());
      if (oldAccount != null) {
        throw new BusinessException("公众号原始id已经存在");
      }
      accountService.save(account);
      j.setSuccess(true);
    } catch (Exception e) {
      logger.error("", e);
      j.setSuccess(false);
      message = "微信公众帐号信息添加失败: " + e.getMessage();
    }

    j.setMsg(message);
    return j;
  }

  /**
   * 更新微信公众帐号信息
   * 
   * @param ids
   * @return
   */
  @RequestMapping(params = "doUpdate")
  @ResponseBody
  public AjaxJson doUpdate(WxAccountEntity weixinAccount, HttpServletRequest request) {
    AjaxJson j = new AjaxJson();

    String message = "微信公众帐号信息更新成功";
    WxAccountEntity t = accountService.get(WxAccountEntity.class, weixinAccount.getId());
    try {
      MyBeanUtils.copyBeanNotNull2Bean(weixinAccount, t);
      accountService.saveOrUpdate(t);
      systemService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO);
    } catch (Exception e) {
      e.printStackTrace();
      message = "微信公众帐号信息更新失败";
      throw new BusinessException(e.getMessage());
    }
    j.setMsg(message);
    return j;
  }

  /**
   * 微信公众帐号信息新增页面跳转
   * 
   * @return
   */
  @RequestMapping(params = "goAdd")
  public ModelAndView goAdd(WxAccountEntity weixinAccount, HttpServletRequest req) {
    if (StringUtil.isNotEmpty(weixinAccount.getId())) {
      weixinAccount = accountService.getEntity(WxAccountEntity.class, weixinAccount.getId());
      req.setAttribute("weixinAccountPage", weixinAccount);
    }
    return new ModelAndView("com/gomore/wechat/mp/account/wxAccount-add");
  }

  /**
   * 微信公众帐号信息编辑页面跳转
   * 
   * @return
   */
  @RequestMapping(params = "goUpdate")
  public ModelAndView goUpdate(WxAccountEntity weixinAccount, HttpServletRequest req) {
    if (StringUtil.isNotEmpty(weixinAccount.getId())) {
      weixinAccount = accountService.getEntity(WxAccountEntity.class, weixinAccount.getId());
      req.setAttribute("weixinAccountPage", weixinAccount);
    }
    return new ModelAndView("com/gomore/wechat/mp/account/wxAccount-update");
  }

  /**
   * 重置Token
   * 
   * @param request
   * @param accountid
   * @return
   * @throws WexinReqException
   */
  @RequestMapping(params = "doResetAccessToken")
  @ResponseBody
  public AjaxJson doResetAccessToken(HttpServletRequest request, String accountid,
      String relationid) throws Exception {
    return accountService.resetAccessToken(accountid);
  }

  /**
   * 方法描述: 查看成员列表 作 者： yiming.zhang 日 期： Dec 4, 2013-8:53:39 PM
   * 
   * @param request
   * @param departid
   * @return 返回类型： ModelAndView
   */
  @RequestMapping(params = "mgrList")
  public ModelAndView mgrList(HttpServletRequest request, String accountid) {
    request.setAttribute("accountid", accountid);
    return new ModelAndView("com/gomore/wechat/mp/account/accountMgrList");
  }

  /**
   * 公众号管理员列表
   * 
   * @param user
   * @param request
   * @param response
   * @param dataGrid
   */
  @RequestMapping(params = "mgrDatagrid")
  public void mgrDatagrid(WxAccountMgrEntity user, HttpServletRequest request,
      HttpServletResponse response, DataGrid dataGrid) {
    String accountId = oConvertUtils.getString(request.getParameter("accountid"));
    Assert.assertArgumentNotEmpty(accountId, "accountId");

    // 查询条件组装器
    CriteriaQuery cq = new CriteriaQuery(WxAccountMgrEntity.class, dataGrid);
    org.jeecgframework.core.extend.hqlsearch.HqlGenerateUtil.installHql(cq, user);
    cq.add(Restrictions.eq("accountId", accountId));
    cq.add();
    this.systemService.getDataGridReturn(cq, true);
    TagUtil.datagrid(response, dataGrid);
  }
}
